<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/22
 * Time: 19:24
 * 代理
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Queue;
use app\common\library\Weixin;
use app\common\model\AgentOrder;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\model\AgentStockRecord;
use app\common\model\Commission;
use app\common\model\GoodsSpec;
use app\common\model\RewardRecord;
use think\Db;
use think\Exception;

class Agent extends Api{
	
	/**
	 * 粉丝
	 */
	public function fans() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
			}
		}
		
		$model = new \app\common\model\Order();
		$rows = Db::name('user')
			->where(['recommend_user_id' => $userId])
			->column('nickname, id as user_id', 'id');
		
		if($rows) {
			
			$order = Db::name('order')
				->where([
					'user_id' => ['in', array_keys($rows)],
					'status' => ['in', [$model::STATUS_SUCCESS, $model::STATUS_SIGN]]
				])
				->group('user_id')
				->column('sum(number) as buy_number', 'user_id');
			
			foreach ($rows as &$row) {
				
				$row['buy_number'] = $order[$row['user_id']] ?? 0;
				
				$row['share_number'] = Db::name('visitor')
					->where(['share_user_id' => $row['user_id']])
					->group('user_id')
					->count();
			}
		}
		
		$this->success('查询成功', array_values($rows));
	}
	
	/**
	 * 订单
	 */
	public function order() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
				$level = $adminLevel['role'];
			}
		}
		
		$model = new \app\common\model\Order();
		$orderType = [$model::TYPE_NORMAL, $model::TYPE_GROUP];
		$where = [
			'o.status' => ['in', [$model::STATUS_SUCCESS, $model::STATUS_SIGN]],
		];
		$userModel = new \app\admin\model\User();
		
		if($level == $userModel::LEVEL_PROMOTION) {
			$where['o.recommend_user_id'] = $userId;
		} else if($level != $userModel::LEVEL_HEADQUARTERS) {
			
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
			
			switch ($level) {
				case $userModel::LEVEL_THEATER:
					$agentWhere['theater_id'] = $shop['id'];
					break;
				case $userModel::LEVEL_CENTER:
					$agentWhere['center_id'] = $shop['id'];
					$orderType[] = $model::TYPE_REWARD;
					break;
				case $userModel::LEVEL_WAREHOUSE:
					$agentWhere['warehouse_id'] = $shop['id'];
					$orderType[] = $model::TYPE_REWARD;break;
				default:
					$agentWhere['id'] = $shop['id'];
			}
			$agentWhere['status'] = AgentShop::STATUS_Y;
			//推荐人是下级或自己
			$agents = Db::name('agentShop')->where($agentWhere)->column('user_id', 'id');
			$agentId = array_merge([$shop['id']], array_keys($agents));
			$promotions = Db::name('promotion')->where(['status' => \app\common\model\Promotion::STATUS_Y, 'agent_shop_id' => ['in', $agentId]])->column('user_id', 'id');
			$ids = array_merge($promotions, $agents, [$shop['user_id']]);
			$where['o.recommend_user_id'] = ['in', $ids];
			
		}
		
		
		$where['o.order_type'] = ['in', $orderType];
		
		$date = $this->request->post('date');
		
		if($date) {
			$date = $date.'-01';
			$startTime = strtotime($date);
			$endTime = strtotime('+1 months', $startTime);
			$where['o.create_time'] = [
				['egt', $startTime],
				['lt', $endTime]
			];
		}
		
		$page = $this->request->post('page', 1, 'intval');
		$count = Db::name('order')->alias('o')->where($where)->count();
		
		$rows = Db::name('order')->alias('o')
			->join('orderGoods g', 'g.order_id = o.id', 'left')
			->where($where)
			->page($page)
			->order('o.create_time desc')
			->field('from_unixtime(o.create_time, \'%y/%m/%d %H:%i:%s\') as date, g.goods_info, o.number, o.amount')
			->select();
		if($rows) {
			foreach ($rows as &$row) {
				$goodsInfo = json_decode($row['goods_info'], true);
				$row['goods_info'] = $goodsInfo;
				$row['goods_name'] = $goodsInfo['spec_name']?:$goodsInfo['name'];
			}
		}
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => $rows,
			'page' => $page
		]);
	}
	
	
	/**
	 * 在售商品及规格
	 */
	public function goodsSpec() {
		$where['status'] = \app\common\model\Goods::STATUS_SALE;
		
		$level = $this->auth->level;
		if($level != \app\admin\model\User::LEVEL_HEADQUARTERS) {
			$where['area'] = $this->area;
		}
		
		$keyword = $this->request->post('keyword');
		$keyword && $where['name'] = ['LIKE', '%'.$keyword.'%'];
		$goods = Db::name('goods')
			->field('id, name, image, area')
			->where($where)
			->select();
		if($goods) {
			foreach ($goods as &$good) {
				$good['name'] = ($good['area'] == \app\admin\model\User::AREA_SZ ? '(深圳)':'').$good['name'];
				$good['spec'] = Db::name('goodsSpec')
					->where(['goods_id' => $good['id'], 'status' => GoodsSpec::STATUS_Y])
					->field('id, name')
					->select();
			}
		}
		
		$this->success('查询成功', $goods);
	}
	
	/**
	 * 手动入库
	 */
	public function inStock() {
		$data = $this->request->post();
		!$data && $this->error('请选择要入库的商品并填写数量');
		
		$userId = $this->auth->id;
		
//		$shop = AgentShop::get(['user_id' => $userId]);
		if($this->auth->level != \app\admin\model\User::LEVEL_THEATER) {
			$this->error('你无权入库');
		}
		$recordModel = new AgentStockRecord();
		
		Db::startTrans();
		try {
			foreach ($data as $key => $number) {
				if($number > 0) {
					$keys = explode('_', $key);
					
					if(!isset($keys[0]) || !isset($keys[1])) {
						throw new Exception('参数错误');
					}
					
					$goods = Db::name('goods')->find($keys[0]);
					if(!$goods) {
						throw new Exception('非法商品');
					}
					
					if($keys[1] != 0) {
						$spec = GoodsSpec::get(['goods_id' => $keys[0], 'id' => $keys[1]]);
						if(!$spec) {
							throw new Exception('存在没有的商品规格');
						}
					}
					$row = Db::name('agentStock')
						->where(['user_id' => $userId, 'goods_id' => $keys[0], 'spec_id' => $keys[1]])
						->find();
					
					if($row) {
						$res = Db::name('agentStock')->where(['id' => $row['id']])->setInc('number', $number);
					} else {
						$res = Db::name('agentStock')
							->insert([
								'user_id' => $userId,
//								'agent_shop_id' => $shop['id'],
								'goods_id' => $keys[0],
								'spec_id' => $keys[1],
								'number' => $number,
								'create_time' => time(),
								'update_time' => time()
							]);
					}
					
					if(!$res) {
						throw new Exception($goods['name'].'入库出错');
					}
					
					$descRecordRes = $recordModel->addRecord($userId, $keys[0], $keys[1], $recordModel::TYPE_IN, $number, '手动进货');
					if(!$descRecordRes) {
						throw new Exception('添加库存记录出错');
					}
				}
			}
			
			Db::commit();
			$this->success('入库成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
	
	/**
	 * 在售商品及规格
	 */
	public function stock() {
		$userId = $this->auth->id;
		if($this->auth->level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
		}
		$where['s.user_id'] = $userId;
		$keyword = $this->request->post('keyword');
		$keyword && $where['g.name'] = ['LIKE', '%'.$keyword.'%'];
		$rows = Db::name('agentStock')->alias('s')
			->join('goods g', 's.goods_id = g.id', 'left')
			->join('goodsSpec gs', 's.spec_id = gs.id', 'left')
			->field('s.goods_id, s.number, g.area, s.spec_id, g.name as goods_name, g.image, gs.name as spec_name, s.spec_id')
			->where($where)
			->select();
		
		$goods = [];
		if($rows) {
			foreach ($rows as $row) {
				if(!isset($goods[$row['goods_id']])) {
					$goods[$row['goods_id']] = [
						'name' => $row['goods_name'],
						'image' => $row['image'],
						'goods_id' => $row['goods_id'],
						'area' => $row['area'],
						'spec' => []
					];
				}
				
					$goods[$row['goods_id']]['spec'][] = [
						'spec_name' => $row['spec_name'] ? : '数量',
						'number' => $row['number'],
						'spec_id' => $row['spec_id']
					];
			}
		}
		
		$this->success('查询成功', array_values($goods));
	}
	
	/**
	 * 添加编辑资料
	 */
	public function edit() {
		$data = $this->request->post();
		$id = $this->request->post('id');
		$check = new \app\common\validate\AgentShop();
		if(!$check->check($data)) {
			$this->error($check->getError());
		}
		
		if(!$id && $this->auth->level > 0) {
			$this->error('你已经有代理身份');
		}
		
		$rid = $this->request->post('rid');
		!$rid && $this->error('请通过上级分享申请');
		
		$userId = $this->auth->id;
		$userModel = new \app\admin\model\User();
		$row = Db::name('agentShop')->where(['user_id' => $userId])->find();
		if(!$id && $row && $row['role'] != $userModel::LEVEL_WAREHOUSE) {
			$this->success('已经填写过资料了', $this->auth->getUserinfo());
		}
		
		$puser = $userModel::get($rid);
		!$puser && $this->error('推荐人不存在');
		
		$area = $this->auth->area ? : 1;
		if($puser['area'] != $area) {
			$this->error('你与推荐人区域不一致');
		}
		
		$role = $puser['level'] - 1;
		$pShop = [];
		if($area == $userModel::AREA_OTHER) {
			if($puser['area'] == $userModel::AREA_OTHER && $puser['level'] < $userModel::LEVEL_WAREHOUSE) {
				$this->error('该上级没有该权限');
			}
			
			if(isset($data['level']) && $data['level'] == $userModel::LEVEL_WAREHOUSE && $puser['level'] == $userModel::LEVEL_WAREHOUSE) {
				$role = $data['level'];
			}
			
			//不是组委会
			if($role != $userModel::LEVEL_CENTER && isset($data['is_group'])) {
				unset($data['is_group']);
			}
			
			$pShop = AgentShop::get(['user_id' => $rid]);
			if(strpos($pShop['provice_id'], $data['provice_id']) === false) {
				$this->error('与上级省份不一致');
			}
			
			if($pShop['role'] == $userModel::LEVEL_CENTER && (strpos($pShop['city_id'], $data['city_id']) === false || strpos($pShop['area_id'], $data['area_id']) === false)) {
				$this->error('与上级省市区不一致');
			}
			
			if($pShop['role'] == $userModel::LEVEL_THEATER) {
				$role = $data['level'] ? : $role;
			}
			
//			if($pShop['is_group'] == 1) {
//				$warehouse = AgentShop::get(['recommend_user_id' => $pShop['user_id'], 'role' => $userModel::LEVEL_WAREHOUSE])->find();
//				if($warehouse) {
//					$this->error('该组委会已经有了提货点');
//				}
//			}
		} else {
			$role = $data['level'] ? : $role;
			if($puser['level'] == $userModel::LEVEL_PROMOTION) {
				$promotion = \app\common\model\Promotion::get(['user_id' => $puser['id']]);
				if($promotion && $promotion['agent_shop_id']) {
					$pShop = AgentShop::get(['id' => $promotion['agent_shop_id']]);
				}
			} else {
				$pShop = AgentShop::get(['user_id' => $rid]);
			}
			
		}
		
		
//		if($role == $userModel::LEVEL_WAREHOUSE) {
//
//			$where['role'] = $userModel::LEVEL_WAREHOUSE;
//			$where['status'] = AgentShop::STATUS_Y;
//
//			$id && $where['id'] = ['neq', $id];
//
//			$row && $where['id'] = ['neq', $row['id']];
//			//200米内不能再入驻
//			$one = Db::name('agentShop')
//				->where($where)
//				->field('ROUND(6378.138 * 2 * ASIN(SQRT( POW( SIN( ('.$data['lat'].' * PI() / 180 - lat * PI() / 180) / 2),2) + COS('.$data['lat'].' * PI() / 180) * COS(lat * PI() / 180) * POW( SIN(('.$data['lng'].' * PI() / 180 - lng * PI() / 180 ) / 2 ),  2))) * 1000) AS distance')
//				->order('distance asc')
//				->find();
//
//			if($one && $one['distance'] < 200) {
//				$this->error('该地点周围200米内已有提货点');
//			}
//		}
		
		
		$status = AgentShop::STATUS_Y;
		$msg = '保存成功';
		if(!$id && in_array($role, [$userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_CENTER])) {
			$status = AgentShop::STATUS_D;
			$msg = '保存成功，请与客服联系开通权限';
		}
		
		if(!$id) {
			$data = array_merge($data, [
				'id' => null,
				'role' => $role,
				'user_id' => $userId,
				'warehouse_id' => $pShop ?( $pShop['role'] == $userModel::LEVEL_WAREHOUSE ? $pShop['id'] : $pShop['warehouse_id']) : '',
				'center_id' => $pShop ?( $pShop['role'] == $userModel::LEVEL_CENTER ? $pShop['id'] : $pShop['center_id']) : '',
				'theater_id' => $pShop ?( $pShop['role'] == $userModel::LEVEL_THEATER ? $pShop['id'] : $pShop['theater_id']) : '',
				'status' => $status,
				'area' => $area,
				'recommend_user_id' => $rid
			]);
		}
		
		$data['area'] = $area;
		
		
		 $model = new AgentShop();
		 $model->startTrans();
		 try {
		 	if($row) {
		 		unset($data['id']);
			    $res = $model
				    ->allowField(true)
				    ->save($data, ['id' => $row['id']]);
		    } else {
			    $res = $model->isUpdate(false)
				    ->allowField(true)
				    ->save($data);
		    }
			
			
			 if($res === false) {
			 	throw new Exception('保存资料出错');
			 }
			
			 $info = $this->auth->getUserinfo();
			 //提货点和发展中心由后台审核开通等级, 场景店直接开通
			 if(!$id && $role == $userModel::LEVEL_SHOP) {
				 $userRes = Db::name('user')->where(['id' => $userId])->update(['level' => $role]);
				 if(!$userRes) {
					 throw new Exception('更改等级出错');
				 }
				 $info['level'] = $role;
			 }
			
			 
			 $model->commit();
			 
			 if(!$row && $status == AgentShop::STATUS_D) {
				 //发送模板消息
				 Queue::addTask('sendTemplate', [
					 'type' => 'applyTips'
				 ]);
			 }
			 $this->success($msg, $info);
		 } catch (Exception $e) {
		 	$model->rollback();
		 	$this->error($e->getMessage());
		 }
		
	}
	
	/**
	 * 获取下级代理，用于发货
	 */
	public function getSon() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level  = $adminLevel['role'];
		}
		
		$userModel = new \app\admin\model\User();
		if($level < $userModel::LEVEL_WAREHOUSE) {
			$this->error('当前帐号没有发货权限');
		}
		
		if($level != $userModel::LEVEL_HEADQUARTERS) {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
		}
		
		$where['a.role'] = $level -1;
		$where['a.area'] = $this->area;
		$where['a.status'] = AgentShop::STATUS_Y;
		switch ($level) {
			case $userModel::LEVEL_THEATER:
				$where['a.theater_id'] = $shop['id'];
				break;
			case $userModel::LEVEL_CENTER:
				$where['a.center_id'] = $shop['id'];
				if($this->area == $userModel::AREA_SZ) {
					$where['a.role'] = $userModel::LEVEL_SHOP;
				}
				break;
			case $userModel::LEVEL_WAREHOUSE:
				$where['a.warehouse_id'] = $shop['id'];
				break;
			default:
				$where['a.role'] = $userModel::LEVEL_THEATER;
				unset($where['a.area']);
		}
		$model = Db::name('agentShop')
			->where($where);
		
		if($level == $userModel::LEVEL_THEATER && $this->area == $userModel::AREA_SZ) {
			$model->whereOr(function($q) use ($userModel, $shop) {
				$q->where(['a.area' => $userModel::AREA_SZ, 'a.role' => $userModel::LEVEL_WAREHOUSE, 'a.theater_id' => $shop['id'], 'a.status' => AgentShop::STATUS_Y]);
			});
		}
		
		$agents = $model->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->field('a.role, a.id, a.name, a.address, u.area, u.reward_number')
			->select();
		
		if($agents) {
			$roleList = $userModel::$levelList;
			foreach ($agents as &$agent) {
				$agent['name'] = '【'.$roleList[$agent['role']].'】'.$agent['name'];
			}
		}
		
		$this->success('查询成功', $agents);
	}
	
	
	/**
	 * 查看对应的下级
	 */
	public function son() {
		$userId = $this->auth->id;
		
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level = $adminLevel['role'];
		}
		
		$role = $this->request->post('role', 2, 'intval');
		$where['role'] = $role;
		$where['status'] = AgentShop::STATUS_Y;
		
		$keyword = $this->request->post('keyword');
		$keyword && $where['name'] = ['like', '%'.$keyword.'%'];
		
		$userModel = new \app\admin\model\User();
		if($level != $userModel::LEVEL_HEADQUARTERS && $level != $userModel::LEVEL_PROMOTION) {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
			
			switch ($level) {
				case $userModel::LEVEL_THEATER:
					$where['theater_id'] = $shop['id'];
					break;
				case $userModel::LEVEL_CENTER:
					$where['center_id'] = $shop['id'];
					break;
				case $userModel::LEVEL_WAREHOUSE:
					$where['warehouse_id'] = $shop['id'];
					break;
				default:
					$where['recommend_user_id'] = $userId;
				
			}
		} else if($level == $userModel::LEVEL_PROMOTION) {
			$where['recommend_user_id'] = $userId;
		}
		
		$page = $this->request->post('page', 1, 'intval');
		$count = Db::name('agentShop')->where($where)->count();
		$rows = Db::name('agentShop')
			->where($where)
			->page($page)
			->column('id, name, destory_number, sale_number, user_id, role', 'user_id');
		
		if($rows) {
			$ids = array_keys($rows);
			
			$date = $this->request->post('date');
			
			
			$dateWhere = ['lt', time()];
			if($date) {
				$date = $date.'-01';
				$startTime = strtotime($date);
				$endTime = strtotime('+1 months', $startTime);
				$dateWhere = [
					['egt', $startTime],
					['lt', $endTime]
				];
			}
			
			//库存
			$stockList = Db::name('agentStock')
				->where(['user_id' => ['in', $ids]])
				->group('user_id')
				->column('sum(number) as stock', 'user_id');
			
			//销售佣金
			$saleList = Db::name('commission')
				->where(['user_id' => ['in', $ids], 'type' => Commission::TYPE_SALE, 'create_time' => $dateWhere])
				->group('user_id')
				->column('sum(amount) as amount', 'user_id');
			
			//核销佣金
			$destoryList = Db::name('commission')
				->where(['user_id' => ['in', $ids], 'type' => Commission::TYPE_GOODS, 'create_time' => $dateWhere])
				->group('user_id')
				->column('sum(amount) as amount', 'user_id');
			
			foreach ($rows as &$row) {
				$row['stock'] = $stockList[$row['user_id']] ?? 0;
				$row['sale_commission'] = $saleList[$row['user_id']] ?? 0;
				$row['destory_commission'] = $destoryList[$row['user_id']] ?? 0;
			}
		}
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => array_values($rows),
			'page' => $page
		]);
	}
	
	
	/**
	 * 下级代言人
	 */
	public function promotion() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level = $adminLevel['role'];
		}
		$userModel = new \app\admin\model\User();
		
		$where = [
			'status' => \app\common\model\Promotion::STATUS_Y
		];
		
		if($level != $userModel::LEVEL_HEADQUARTERS && $level != $userModel::LEVEL_PROMOTION) {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
			switch ($level) {
				case $userModel::LEVEL_THEATER:
					$shopWhere['theater_id'] = $shop['id'];
					break;
				case $userModel::LEVEL_CENTER:
					$shopWhere['center_id'] = $shop['id'];
					break;
				case $userModel::LEVEL_WAREHOUSE:
					$shopWhere['warehouse_id'] = $shop['id'];
					break;
				default:
					$shopWhere['id'] = $shop['id'];
			}
			$shopWhere['status'] = AgentShop::STATUS_Y;
			$ids = Db::name('agentShop')->where($shopWhere)->column('user_id', 'id');
			$ids[$shop['id']] = $shop['user_id'];
			$where['recommend_user_id'] = ['in', array_values($ids)];
	
		} else if($level == $userModel::LEVEL_PROMOTION) {
			$where['recommend_user_id'] = $userId;
		}
		
		$page = $this->request->post('page', 1, 'intval');
		
		$count = Db::name('promotion')->where($where)->count();
		$rows = Db::name('promotion')
			->where($where)
			->field('id, name, sale_number')
			->page($page)
			->order(['create_time' => 'desc'])
			->select();
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => $rows,
			'page' => $page
		]);
	}
	
	
	/**
	 * 发货
	 */
	public function sendGoods() {
		$postData = $this->request->post();
		$signAgentId = $this->request->post('agent_id');
		!$signAgentId && $this->error('收货下级不能为空');
		
		
		$shipName = $this->request->post('ship_name');
		!$shipName && $this->error('快递名称不能为空');
		
		$shipNo = $this->request->post('ship_no');
		!$shipNo && $this->error('快递单号不能为空');
		
		$numberList = $postData['number_list'];
		!$numberList && $this->error('出货商品数量不能为空');
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
				$level = $adminLevel['role'];
			}
		}
		
		$userModel = new \app\admin\model\User();
		if($level < $userModel::LEVEL_WAREHOUSE) {
			$this->error('当前帐号没有发货权限');
		}
		
		if($level != $userModel::LEVEL_HEADQUARTERS) {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
		} else {
			$shop = '';
		}
		
		$agentShop = AgentShop::get($signAgentId);
		!$agentShop && $this->error('收货下级不存在');
		
		
		Db::startTrans();
		try {
			$recordModel = new AgentStockRecord();
					$no = time().mt_rand(10000, 99999);
			$data = [];
			foreach ($numberList as $key => $number) {
				if($number > 0) {
					$keys = explode('_', $key);
					
					if(!isset($keys[0]) || !isset($keys[1])) {
						throw new Exception('参数错误');
					}
					
					$goodsId = $keys[0];
					$specId = $keys[1];
					
					if($shop) {
						$row = Db::name('agentStock')->alias('as')
							->join('goods g', 'as.goods_id = g.id', 'left')
							->join('goodsSpec s', 's.id = as.spec_id', 'left')
							->where(['as.user_id' => $userId, 'as.goods_id' => $goodsId, 'as.spec_id' => $specId])
							->field('as.id, g.name, s.name as spec_name, as.number')
							->find();
						if(!$row) {
							throw new Exception('要发货的商品不存在');
						}
						
						if($row['number'] < $number) {
							throw new Exception($row['name'].$row['spec_name'].'库存不足');
						}
						
					
						//发货数量加现在库存不能超过系统设计的数量
						$warning = Db::name('stockWarning')
							->where(['goods_id' =>  $goodsId, 'spec_id' => $specId, 'level' => $agentShop['role']])
							->find();
						if($warning && $warning['number'] > 0) {
							$sonStock = Db::name('agentStock')
								->where(['user_id' => $agentShop['user_id'], 'goods_id' => $goodsId, 'spec_id' => $specId])
								->field('id, number')
								->find();
							
							$sonStockNumber = $sonStock ? $sonStock['number'] : 0;
							if($number + $sonStockNumber > $warning['number']) {
								throw new Exception($row['name'].$row['spec_name'].'发货数量加库存数量超过了系统设置最大数量,剩余发货数量为【'.($warning['number']-$sonStockNumber).'】');
							}
						}
						
						//减库存，加库存记录
						$descRes = Db::name('agentStock')
							->where(['id' => $row['id']])
							->setDec('number', $number);
						
						if(!$descRes) {
							throw new Exception('减少库存出错');
						}
						
						$descRecordRes = $recordModel->addRecord($userId, $goodsId, $specId, $recordModel::TYPE_OUT, -$number, '发货批次号'.$no);
						if(!$descRecordRes) {
							throw new Exception('添加减少库存记录出错');
						}
					}
				
					
				
					
					$data[] = [
						'no' => $no,
						'send_agent_id' => $shop ? $shop['id'] : 0,
						'sign_agent_id' => $signAgentId,
						'goods_id' => $goodsId,
						'spec_id' => $specId,
						'number' => $number,
						'ship_name' => $shipName,
						'ship_no' => $shipNo,
						'create_time' => time(),
						'update_time' => time()
					];
				}
			}
			
			if($data) {
				$orderRes = Db::name('agentShipment')
					->insertAll($data);
				if(!$orderRes) {
					throw new Exception('添加发货订单出错');
				}
			}
			
			//减少奖励数量
			if(isset($postData['destroy_number']) && $postData['destroy_number'] > 0) {
				$user = Db::name('user')->find($agentShop['user_id']);
				if($user['reward_number'] < $postData['destroy_number']) {
					throw new Exception('当前下级剩余奖励数量为'.$user['reward_number']);
				}
				
				
				$userRes = Db::name('user')
						->where(['id' => $agentShop['user_id']])
					->setDec('reward_number', $postData['destroy_number']);
				if(!$userRes) {
					throw new Exception('减少奖励数量出错');
				}
				
				$recordRes = RewardRecord::addRecord($agentShop['user_id'], -$postData['destroy_number'], '已发货奖励');
				if(!$recordRes) {
					throw new Exception('添加奖励记录出错');
				}
				
				if($shop && $shop['role'] == $userModel::LEVEL_THEATER) {
					$theaterNumberRes = Db::name('user')
						->where(['id' => $shop['user_id']])
						->setInc('reward_number', $postData['destroy_number']);
					if(!$theaterNumberRes) {
						throw new Exception('添加战区奖励数量出错');
					}
					$recordRes = RewardRecord::addRecord($shop['user_id'], $postData['destroy_number'], '核销下级添加');
					if(!$recordRes) {
						throw new Exception('添加战区奖励记录出错');
					}
				}
			}
			
			\app\common\model\Message::add($agentShop['user_id'], '签收提醒', '你的上级已发货，请注意查收入库!');
			Db::commit();
			
			$formIdRow = Db::name('formId')->alias('f')
				->join('user u', 'f.user_id = u.id', 'left')
				->where(['f.user_id' => $agentShop['user_id'], 'number' => 0, 'create_time' => ['egt', strtotime('-7 days')]])
				->field('f.id, u.smallapp_openid, f.form_id')
				->find();
			
			if($formIdRow) {
				$config= config('weixin');
				$templateId = $config['smallapp']['message_template']['send_tips'];
				$data = [
					'keyword1' => ['value' => $agentShop['name']],
					'keyword2' => ['value' => '你的上级已发货，请注意查收入库!'],
				];
				$obj = new Weixin($config['smallapp']['app_id']);
				$page = 'pages/index/index';
				$res = $obj->sendTemplate($formIdRow['smallapp_openid'], $templateId, $formIdRow['form_id'],$data, $page);
				if($res === true) {
					Db::name('formId')->where(['id' => $formIdRow['id']])->setInc('number');
				}
			}
			
			//添加库存检测任务
			if($shop) {
				foreach ($numberList as $key => $number) {
					if($number > 0) {
						$keys = explode('_', $key);
						$goodsId = $keys[0];
						$specId = $keys[1];
						Queue::addTask('checkStock', ['id' => $shop['id'], 'goods_id' => $goodsId, 'spec_id' => $specId]);
					}
				}
			}
			$this->success('发货成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	
		


	}
	
	
	/**
	 * 进出货订单
	 */
	public function stockOrder() {
		$type = $this->request->post('type', 'sign');
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level  = $adminLevel['role'];
		}
		
		if($level == \app\admin\model\User::LEVEL_HEADQUARTERS) {
			$shop['id'] = 0;
		} else {
			$shop = AgentShop::get(['user_id' => $userId]);
			
			!$shop && $this->error('权限不足');
		}
	
		
		if($type == 'sign') {
			$where['o.sign_agent_id'] = $shop['id'];
		} else {
			$where['o.send_agent_id'] = $shop['id'];
		}
		
		$rows = Db::name('agentShipment')->alias('o')
			->join('goods g', 'o.goods_id = g.id', 'left')
			->join('agentShop a', 'o.sign_agent_id = a.id', 'left')
			->join('goodsSpec s', 'o.spec_id = s.id', 'left')
			->where($where)
			->field('o.id, o.no, o.number, o.ship_name, o.ship_no, o.status, from_unixtime(o.create_time, \'%Y/%m/%d %H:%i:%s\') as date, g.image, g.name, s.name as spec_name, a.name as sign_name')
			->order(['o.create_time' => 'DESC'])
			->select();
		
		$orders = [];
		if($rows) {
			$statusList = AgentShipment::$statusList;
			foreach ($rows as $row) {
				if(!isset($orders[$row['no']])) {
					$orders[$row['no']] = [
						'no' => $row['no'],
						'date' => $row['date'],
						'ship_name' => $row['ship_name'],
						'ship_no' => $row['ship_no'],
						'status' => $row['status'],
						'status_text' => $statusList[$row['status']],
						'name' => $row['sign_name'],
						'goods' => [
						
						]
					];
				}
				
				$orders[$row['no']]['goods'][] = $row;
			}
		}
		
		$this->success('查询成功', array_values($orders));
	}
	
	/**
	 * 签收入库
	 */
	public function sign() {
		$no = $this->request->post('no');
		!$no && $this->error('请选择要签收的订单');
		
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
			}
		}
		$shop = AgentShop::get(['user_id' => $userId]);
		!$shop && $this->error('权限不足');
		
		$model = new AgentShipment();
		$res = $model->sign($no, $shop['id'], $userId);
		if($res) {
			$this->success('入库成功');
		} else {
			$this->error($model->getError());
		}
	}
	
	/**
	 * 查询及核销订单
	 */
	public function orderDetail() {
			$code = $this->request->post('code');
			!$code && $this->error('参数错误');
		
			$userId = $this->auth->id;
			$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
		}
			
			$agent = AgentShop::get(['user_id' => $userId]);
			
			$userModel = new \app\admin\model\User();
			
			//广东省的场景店，提货点和发展中心都能核销，其它地区发展中心不能核销
			$roleList = [
				$userModel::LEVEL_SHOP,$userModel::LEVEL_WAREHOUSE
			];
			
			if($this->area == $userModel::AREA_SZ) {
				$roleList[] = $userModel::LEVEL_CENTER;
			}
			
			if(!$agent || !in_array($agent['role'], $roleList)) {
				$this->error('没有核销权限');
			}
			
			if($agent['status'] == AgentShop::STATUS_D) {
				$this->error('你的代理身份已被禁用');
			}
			
			$model = new \app\common\model\Order();
			$order = $model->where(['code' => $code])->find();
			!$order && $this->error('订单不存在');
			
			if($order['status'] != $model::STATUS_SIGN) {
				$this->error('非待核销订单');
			}
			
			
			$goods = Db::name('orderGoods')
				->where(['order_id' => $order['id']])
				->find();
			
			$goods['goods_info'] = json_decode($goods['goods_info'], true);
			
			$order['goods'] = [$goods];
			$type = $this->request->post('type', 'check');
			
			//查询订单信息
			if($type == 'check') {
				$this->success('查询成功', $order);
			} else {
				//核销
				$force = $this->request->post('force', 0, 'intval');
				$res = $model->destructOrder($order, $agent, $force);
				if($res === true) {
					//添加库存检测任务
					Queue::addTask('checkStock', ['id' => $agent['id'], 'goods_id' => $goods['goods_id'], 'spec_id' => $goods['goods_info']['spec_id']]);
					
					$this->success("核销成功");
				} elseif($res == -1){
					$this->error($model->getError(),[], -1);
				} else {
					$this->error($model->getError());
				}
			}
	}
	
	
	/**
	 * 代理入驻检查
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function check() {
		$rid = $this->request->post('id');
		$userId = $this->auth->id;
		$level = $this->auth->level;
		
		$rShop = null;
		if($rid) {
			$rShop = Db::name('user')->alias('u')
				->join('agentShop a', 'u.id = a.user_id', 'left')
				->where(['u.id' => $rid])
				->field('a.id, a.role, a.user_id, u.area')
				->find();
			
			if($rShop['area'] != $this->auth->area) {
				$this->error('你与推荐人不在同一区域', $rShop);
			}
		}
		
		
		$order = Db::name('agentOrder')->where(['user_id' => $userId])->find();
		if($order && $order['status'] == AgentOrder::STATUS_Y) {
			$payStatus = 1;
		} else {
			$payStatus = 0;
		}
		
		$shop = Db::name('agentShop')->where(['user_id' => $userId])
			->field('id, role, user_id, warehouse_id')->find();
		
		$row = Db::name('agentShop')->alias('s')
			->join('area p', 's.provice_id = p.id', 'left')
			->join('area c', 's.city_id = c.id', 'left')
			->join('area a', 's.area_id = a.id', 'left')
			->where(['s.user_id' => $this->auth->id])
			->field('s.id, s.name, s.mobile, s.image, s.license_image, s.card_images,
			s.address, s.lat, s.lng, s.content, s.recommend_user_id as rid,
			s.provice_id, s.city_id, area_id, s.role as level, s.location_address,
			s.is_group, p.name as province, c.name as city, a.name as area, s.username')
			->find();
		if($row) {
			$row['card_images'] = array_filter(explode(',', $row['card_images']));
		}
		
		$this->success('查询成功', [
			'level' => $level,
			'payStatus' => $payStatus,
			'agentInfo' => $row,
			'rShop' => $rShop && $rShop['id'] ? 1 : 0,
			'rid' => $order ? $order['recommend_user_id'] : '',
			'openLevel' => $order ? $order['level'] : '',
			'warehouse_id' => $shop ? $shop['warehouse_id'] : ''
		]);
	}
	
	/**
	 * 奖励数量明细
	 */
	public function rewardNumber() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level = $adminLevel['role'];
		}
		
		$userModel = new \app\admin\model\User();
		if(!in_array($level, [$userModel::LEVEL_HEADQUARTERS, $userModel::LEVEL_CENTER, $userModel::LEVEL_THEATER])) {
			$this->error('没权查看');
		}
		
		
		if($level == $userModel::LEVEL_HEADQUARTERS) {
			$where['a.role'] = ['in', [$userModel::LEVEL_CENTER, $userModel::LEVEL_WAREHOUSE]];
		} else if($level == $userModel::LEVEL_THEATER) {
			$where['a.role'] = ['in', [$userModel::LEVEL_CENTER, $userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_SHOP]];
		} else {
			$where = [
				'a.recommend_user_id' => $userId,
				'a.role' => $userModel::LEVEL_SHOP
			];
		}
		
		$where['a.gift_number'] = ['gt', 0];
		$where['a.status'] = AgentShop::STATUS_Y;
		
		
		$page = $this->request->post('page', 1, 'intval');
		
		$count = Db::name('agentShop')->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->where($where)
			->count();
		
		$list = Db::name('agentShop')->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->where($where)
			->field('a.name, a.gift_number as number')
			->page($page)
			->select();
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list,
			'page' => $page
		]);
	}
	
	/**
	 * 奖励记录
	 */
	public function rewardRecord() {
		$userId = $this->auth->id;
		if($this->auth->level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
		}
		$where['r.user_id'] = $userId;
		$page = $this->request->post('page', 1, 'intval');
		
		$count = Db::name('rewardRecord')->alias('r')
			->where($where)
			->count();
		
		$list = Db::name('rewardRecord')->alias('r')
			->join('agentShop a', 'r.agent_id = a.user_id', 'left')
			->where($where)
			->field('r.id, from_unixtime(r.create_time, \'%Y/%m/%d %H:%i\') as date, r.number, r.remark, r.agent_id, a.name')
			->page($page)
			->select();
		
		if($list) {
			foreach ($list as &$item) {
				$item['remark'] = $item['agent_id'] ? $item['name'] : $item['remark'];
			}
		}
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list,
			'page' => $page
		]);
	}
	
	/**
	 * 代理订单
	 */
	public function orderList() {
		$type = $this->request->post('type', 'self');
		$page = $this->request->post('page', 1, 'intval');
		$userId = $this->request->post('user_id');
		$user = \app\admin\model\User::get($userId);
		
		if($type == 'self') {
			$sonUserIds = [$userId];
		} else {
			$agentModel = new AgentShop();
			$sonUserIds = $agentModel->getSonIds($userId, $user['level']);
			
			$key = array_search($userId, $sonUserIds);
			if($key >= 0) {
				unset($sonUserIds[$key]);
			}
		}
		if($sonUserIds) {
			
			$date = $this->request->post('date');
			
			$orderModel = new \app\common\model\Order();
			$where = [
				'o.recommend_user_id' => ['in', $sonUserIds],
				'o.status' => ['in', [$orderModel::STATUS_SIGN, $orderModel::STATUS_SUCCESS]],
				'o.order_type' => ['in', [$orderModel::TYPE_NORMAL, $orderModel::TYPE_GROUP]],
			];
			
			if($date) {
				$date = $date.'-01';
				$startTime = strtotime($date);
				$endTime = strtotime('+1 months', $startTime);
				$where['o.create_time'] = [
					['egt', $startTime],
					['lt', $endTime]
				];
			}
			
			
			$count = Db::name('order')
				->alias('o')
				->where($where)
				->field('sum(amount) as order_amount, sum(number) as goods_number, count(id) as order_number')
				->find();
			
			$list = Db::name('order')->alias('o')
				->join('orderGoods g', 'o.id = g.order_id', 'left')
				->join('promotion p', 'o.recommend_user_id = p.user_id', 'left')
				->join('agentShop a', 'o.recommend_user_id = a.user_id', 'left')
				->where($where)
				->field('o.id, o.order_no, o.number, o.amount, from_unixtime(o.create_time, \'%Y-%m-%d %H:%i:%s\') as date, g.goods_info, p.name as promotion_name, a.name as agent_name')
				->page($page)
				->select();
			
			if (!empty($list)) {
				if($list) {
					foreach ($list as &$item) {
						$goodsInfo = json_decode($item['goods_info'], true);
						$item['goods_image'] = $goodsInfo['image'];
						$item['goods_name'] = $goodsInfo['name'];
						$item['spec_name'] = $goodsInfo['spec_name'];
						unset($item['goods_info']);
					}
				}
			}
		} else {
			$count = [
				'order_amount' => 0,
				'order_number' => 0,
				'goods_number' => 0
			];
			$list = [];
		}
		
		$this->success('查询成功', [
			'page' => $page,
			'total' => $count['order_number'] ?:0,
			'order_amount' => $count['order_amount'] ?:0,
			'goods_number' => $count['goods_number'] ?:0,
			'list' => $list,
		]);
	}
	
	
	/**
	 * 核销记录
	 */
	public function destoryList() {
		$page = $this->request->post('page', 1, 'intval');
		$userId = $this->request->post('user_id');
		$agent = AgentShop::get(['user_id' => $userId]);
		
		if($agent) {
			
			$date = $this->request->post('date');
			
			
			$where['as.agent_shop_id'] = $agent['id'];
			if($date) {
				$date = $date.'-01';
				$startTime = strtotime($date);
				$endTime = strtotime('+1 months', $startTime);
				$where['as.create_time'] = [
					['egt', $startTime],
					['lt', $endTime]
				];
			}
			
			$count = Db::name('agentShip')
				->alias('as')
				->where($where)
				->field('count(id) as number, sum(number) as goods_number')
				->find();
			
			
			$list = Db::name('agentShip')->alias('as')
				->join('order o', 'o.id = as.order_id', 'left')
				->join('orderGoods g', 'o.id = g.order_id', 'left')
				->join('promotion p', 'o.recommend_user_id = p.user_id', 'left')
				->join('agentShop a', 'o.recommend_user_id = a.user_id', 'left')
				->where($where)
				->field('o.id, o.order_no, as.number, o.amount, from_unixtime(as.create_time, \'%Y-%m-%d %H:%i:%s\') as date, g.goods_info, p.name as promotion_name, a.name as agent_name')
				->page($page)
				->select();
			
			if($list) {
				foreach ($list as &$item) {
					$goodsInfo = json_decode($item['goods_info'], true);
					$item['goods_image'] = $goodsInfo['image'];
					$item['goods_name'] = $goodsInfo['name'];
					$item['spec_name'] = $goodsInfo['spec_name'];
					unset($item['goods_info']);
				}
			}
		} else {
			$count = [
				'number' => 0,
				'goods_number' => 0
			];
			$list = [];
		}
		
		$this->success('查询成功', [
			'page' => $page,
			'total' => $count['number'] ? : 0,
			'goods_number' => $count['goods_number'] ? : 0,
			'list' => $list
		]);
	}
	
	/**
	 * 代理信息（用于编辑)
	 */
	public function info() {
		$row = Db::name('agentShop')->alias('s')
			->join('area p', 's.provice_id = p.id', 'left')
			->join('area c', 's.city_id = c.id', 'left')
			->join('area a', 's.area_id = a.id', 'left')
			->where(['s.user_id' => $this->auth->id])
			->field('s.id, s.name, s.mobile, s.image, s.license_image, s.card_images,
			s.address, s.lat, s.lng, s.content, s.recommend_user_id as rid,
			s.provice_id, s.city_id, area_id, s.role as level, s.location_address,
			s.is_group, p.name as province, c.name as city, a.name as area, s.username')
			->find();
		
		$row['card_images'] = array_filter(explode(',', $row['card_images']));
		$this->success('查询成功', $row);
	}
}
